package com.sky.controller.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.internal.org.objectweb.asm.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisTemplate<String,List<DishVO>> redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        log.info("根据分类id{}查询菜品",categoryId);
        log.info("正在读取缓存数据");
//        构建RedisKey
        String redis_key = "dish_" + categoryId;
//        去缓存中查询数据
        ValueOperations<String,List<DishVO>> operations = redisTemplate.opsForValue();
//        目标数据不在缓存中，再去数据库获取
        List<DishVO> dishs= (List<DishVO>) operations.get(redis_key);
//        String s = operations.get(redis_key);
//        List<DishVO> dishs = objectMapper.readValue(s,new TypeReference<List<DishVO>>() {});
        if (dishs != null && dishs.size() > 0){
            log.info("获取缓存数据{}",dishs);
            return Result.success(dishs);
        }
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品

        List<DishVO> list = dishService.listWithFlavor(dish);
        log.info("写入缓存数据");
        operations.set(redis_key,list);
        return Result.success(list);
    }

}
